package com.example.superjson.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.ParseException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.util.Log;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

public class JavaToJson {
	
	private static ObjectMapper mapper = new ObjectMapper();
	public static String transToJson(Object obj) throws IOException {
		return mapper.writeValueAsString(obj);
	}
	
	@SuppressWarnings("unchecked")
	public static Object transToJava(String json, Class objClass) throws JsonParseException, 
	     JsonMappingException, IOException {
		return mapper.readValue(json, objClass);
	}

	public static Map readjson(JsonParser parser) throws IOException, ParseException {
		// if (jp.nextToken().equals(JsonToken.BEGIN_OBJECT)) {
		// throw new IOException("Expected data to start with an Object");
		// }
		Map<String, ArrayList<StdJson>> tmpmap = new HashMap<String, ArrayList<StdJson>>();

		ArrayList<StdJson> tmplist = new ArrayList<StdJson>();

		String entryName = "entry";
		while (!parser.isClosed()) {
			// get the token
			JsonToken token = parser.nextToken();
			// if its the last token then we are done
			if (token == null)
				break;
			// we want to look for a field that says dataset
			// while(!((parser.getCurrentToken() == JsonToken.START_ARRAY) &&
			// (parser.nextValue() != JsonToken.START_ARRAY ))){
			// if(parser.getCurrentToken() != JsonToken.END_ARRAY &&
			// parser.getCurrentToken() != null && (parser.nextValue() != null
			// && parser.getText() != null)){
			// Log.d("TX",parser.getText());
			// parser.nextToken();
			// }else{
			// break;
			// }
			// }
			parser.nextToken();
			StdJson sj = new StdJson();
			if (parser.getCurrentToken() == JsonToken.START_ARRAY) {
				parser.nextToken();
				sj.setType(parser.getIntValue());
				Log.d("T1", "" + parser.getIntValue());
				parser.nextToken();
				// if (sj.getAxisType() == int.class) {
				// sj.setAxis(String.valueOf(parser.getIntValue()));
				// } else {
				sj.setAxis(parser.getText());
				// }
				Log.d("T2", parser.getText());
				String[] datatmp = new String[sj.getSize()];
				for (int i = 0; i < sj.getSize(); i++) {
					parser.nextToken();
					datatmp[i] = parser.getText();
					Log.d("T" + (3 + i), datatmp[i]);
				}
				Log.d("OOOO", "" + sj.getSize());
				sj.setData(datatmp);
				sj.drawAll();

				tmplist.add(sj);
			}
		}
		tmpmap.put(entryName, tmplist);
		return tmpmap;
	}
}
